#include "Manage.h"

char gapmode[20];
int gmycount = 0;

/*****************************
**函数功能：获取APmode  
**参数：value：存放AP型号的缓冲区
**返回值：无
*****************************/
void Get_AP_Info_ANY(char *apmode, char *apver)
{
	FILE *rfd = NULL;
	memset(gapmode, '\0', 20);
	rfd = fopen("/etc/APmode", "r");
	if (!rfd)
	{
		printf("open error!\n");
		return;
	}
	fscanf(rfd, "%s\n", apver);
#ifdef WTP_9341  //ANY-AP300A1             9341AP
	memcpy(apmode, "ANY-AP300A1", 11);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
#ifdef WTP_7620  //ANY-AP300RN            7620AP
	memcpy(apmode, "ANY-AP300RN", 11);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
#if defined (WTP_9557) || defined (WTP_9557_DEF) //ANY-AP1200Q2          9557双频AP
	memcpy(apmode, "ANY-AP1200Q2", 12);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
	printf("APmode is %s, version is %s\n", apmode, apver);
	fclose(rfd);
	return;
}
/*****************************
**函数功能：获取APmode  
**参数：value：存放AP型号的缓冲区
**返回值：无
*****************************/
void Get_AP_Info_DB(char *apmode, char *apver)
{
	FILE *rfd = NULL;
	memset(gapmode, '\0', 20);
	rfd = fopen("/etc/APmode", "r");
	if (!rfd)
	{
		printf("open error!\n");
		return;
	}
	fscanf(rfd, "%s\n", apver);
#ifdef WTP_9341  //DB-AP300A1             9341AP
	memcpy(apmode, "DB-AP300A1", 10);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
#ifdef WTP_7620  //DB-AP300RN            7620AP
	memcpy(apmode, "DB-AP300RN", 10);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
#if defined (WTP_9557) ||defined (WTP_9557_DEF) //DB-AP1200Q2          9557双频AP
	memcpy(apmode, "DB-AP1200Q2", 11);
	sprintf(gapmode, "%s%s", apmode, apver);
#endif
	printf("APmode is %s, version is %s\n", apmode, apver);
	fclose(rfd);
	return;
}
/*****************************
**函数功能：配置数据库查询
**参数：mysql-数据库连接字，apmac-AP的mac地址，set-AP设置结构体，myipaddr-AP的IP地址
**返回值：int类型 fAILED-失败，SUCCESS-成功
*****************************/
int Read_Manage_DataBS(MYSQL mysql, char* apmac, APWLANSET *set, char *myipaddr, int model_type)
{
	if (!apmac || strlen(apmac) < 17)
		return fAILED;
	MYSQL_RES *res;
	MYSQL_ROW row;
	int flag, t, i;
	char dbvar[1024];
	memset(dbvar, '\0', 1024);
#if defined (WTP_9557) || defined (WTP_9557_DEF)
	sprintf(dbvar, "SELECT Refresh,TxPower,Channel,SSID,Encrypt,`Key`,upauto,limit_sig,txtwo,chtwo,ssidtwo,enctwo,keytwo FROM %s where APmac like \"%s\"", DATABS_APMANAGE_TAB, apmac);
#else
	sprintf(dbvar, "SELECT Refresh,TxPower,Channel,SSID,Encrypt,`Key`,upauto,limit_sig FROM %s where APmac like \"%s\"", DATABS_APMANAGE_TAB, apmac);
#endif
	printf("read db conmand is %s!\n", dbvar);
	flag = mysql_real_query(&mysql, dbvar, (unsigned int)strlen(dbvar));
	if (flag)
	{
		printf("Quert:\n");
		return fAILED;
	}
	res = mysql_store_result(&mysql);
	i = mysql_num_fields(res);
	row = mysql_fetch_row(res);
	if (0 == row) //查询成功但是没有数据
	{
		printf("No data for this mac(%s),need use default config!\n", apmac);
		return fAILED;
	}
	for (t = 0; t < i; t++)
	{
		printf("%s\t", row[t]);
		switch (t)
		{
		case CON_REFRESH:    // 0是否自动更新配置
			strcpy((*set).refresh, row[t]);
			break;
		case CON_TXPOWER:   // 1 功率
			strcpy((*set).txpower, row[t]);
			break;
		case CON_CHANNEL:   // 2 信道
			strcpy((*set).channel, row[t]);
			break;
		case CON_SSID:     // 3 无线名称
			strcpy((*set).ssid, row[t]);
			break;
		case CON_ENCTYPT:  // 4 加密方式	
			strcpy((*set).encrypt, row[t]);
			break;
		case CON_KEY:      // 5 密码
			strcpy((*set).key, row[t]);
			break;
		case IMG_UPAUTO:   // 6 是否自动升级
			strcpy((*set).upauto, row[t]);
			break;
		case LIMIT_SIG:    // 7 显示信号强度断开
			strcpy((*set).max_listen, row[t]);
			break;
		case CON_TXPOWER_TWO:	// 8 功率
			strcpy((*set).txpower_t, row[t]);
			break;
		case CON_CHANNEL_TWO:	// 9 信道
			strcpy((*set).channel_t, row[t]);
			break;
		case CON_SSID_TWO:		// 10 无线名称
			strcpy((*set).ssid_t, row[t]);
			break;
		case CON_ENCTYPT_TWO:	   // 11 加密方式	
			strcpy((*set).encrypt_t, row[t]);
			break;
		case CON_KEY_TWO:			 // 12 密码
			strcpy((*set).key_t, row[t]);
			break;
		default:
			break;
		}
	}
	printf("\n");
	memset(dbvar, '\0', sizeof(dbvar));
	if (!strcmp(apmac, DEFAULT_CONFIG_M))
	{
		if (DEFCONFIG == model_type)//是恢复默认配置
		{
#if defined (WTP_9557) || defined (WTP_9557_DEF)
			sprintf(dbvar, "UPDATE %s SET Refresh = 'y',TxPower= '%s',Channel= '%s',SSID= '%s',Encrypt= '%s',`Key`= '%s',upauto= '%s',APIP= '%s',APstate= '1',APmode= '%s',txtwo= '%s',chtwo= '%s',ssidtwo= '%s',enctwo= '%s',keytwo= '%s' WHERE APmac='%s'",
				DATABS_APMANAGE_TAB, (*set).txpower, (*set).channel, (*set).ssid, (*set).encrypt, (*set).key, (*set).upauto, myipaddr, gapmode, (*set).txpower_t, (*set).channel_t, (*set).ssid_t, (*set).encrypt_t, (*set).key_t, gAP_macaddr);
#else	
			sprintf(dbvar, "UPDATE %s SET Refresh = 'y',TxPower= '%s',Channel= '%s',SSID= '%s',Encrypt= '%s',`Key`= '%s',upauto= '%s',APIP= '%s',APstate= '1',APmode= '%s' WHERE APmac='%s'",
				DATABS_APMANAGE_TAB, (*set).txpower, (*set).channel, (*set).ssid, (*set).encrypt, (*set).key, (*set).upauto, myipaddr, gapmode, gAP_macaddr);
#endif
			}
		else//新AP获取默认配置
		{
#if defined (WTP_9557) || defined (WTP_9557_DEF)
			sprintf(dbvar, "INSERT INTO %s(APmac,Refresh,TxPower,Channel,SSID,Encrypt,`Key`,upauto,APIP,APstate,APmode,limit_sig,txtwo,chtwo,ssidtwo,enctwo,keytwo) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%c','%s','%s','%s','%s','%s','%s','%s')",
				DATABS_APMANAGE_TAB, gAP_macaddr, (*set).refresh, (*set).txpower, (*set).channel, (*set).ssid, (*set).encrypt, (*set).key, (*set).upauto, myipaddr, '1', gapmode, (*set).max_listen, (*set).txpower_t, (*set).channel_t, (*set).ssid_t, (*set).encrypt_t, (*set).key_t);
#else
			sprintf(dbvar, "INSERT INTO %s(APmac,Refresh,TxPower,Channel,SSID,Encrypt,`Key`,upauto,APIP,APstate,APmode,limit_sig) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%c','%s','%s')",
				DATABS_APMANAGE_TAB, gAP_macaddr, (*set).refresh, (*set).txpower, (*set).channel, (*set).ssid, (*set).encrypt, (*set).key, (*set).upauto, myipaddr, '1', gapmode, (*set).max_listen);
#endif
		}
	}
	else
	{
		if (gmycount >= 2)
		{
			sprintf(dbvar, "UPDATE %s SET APstate='1',APmode='%s',APIP='%s' WHERE APmac='%s'", DATABS_APMANAGE_TAB, gapmode, myipaddr, gAP_macaddr);
			gmycount = 0;
		}
		else{
			sprintf(dbvar, "UPDATE %s SET APstate='1',APmode='%s' WHERE APmac='%s'", DATABS_APMANAGE_TAB, gapmode, gAP_macaddr);
		}
		gmycount++;
	}
	flag = mysql_real_query(&mysql, dbvar, (unsigned int)strlen(dbvar));
	printf("c conmand is %s\n", dbvar);
	if (flag)
	{
		printf("config db error!\n conmand is %s\n", dbvar);
		return fAILED;
	}
	printf("Insert data success!\n");
	return SUCCESS;
}
/*****************************
**函数功能：更新数据库
**参数：mysql-数据库连接字，apmac-AP的mac地址，type-AP操作（REBOOTAP 1 AP要重启，重启前更新数据库，DEFCONFIG 0 AP配置复位，复位钱更新数据库）
**返回值：int类型 fAILED-失败，SUCCESS-成功
*****************************/
int Updata_Manage_DataBS(MYSQL mysql, char *apmac, int type)
{
	char updata[256] = {'\0'};
	int flag;
	if (REBOOTAP == type)
	{
		sprintf(updata, "UPDATE %s SET upauto = 'n',APstate='1', Refresh = 'y' WHERE APmac = '%s'", DATABS_APMANAGE_TAB, apmac);
	}
	else if (DEFCONFIG == type)
	{
		sprintf(updata, "UPDATE %s SET upauto = 'n', APstate='1' WHERE APmac = '%s'", DATABS_APMANAGE_TAB, apmac);
	}
	else if (UPDATASYS == type)
	{
		sprintf(updata, "UPDATE %s SET upauto = 'n', APstate='1', Refresh = 'y' WHERE APmac = '%s'", DATABS_APMANAGE_TAB, apmac);
	}
	else
	{
		sprintf(updata, "UPDATE %s SET APstate='1' WHERE APmac = '%s'", DATABS_APMANAGE_TAB, apmac);
	}
	printf("update db is %s\n", updata);
	flag = mysql_real_query(&mysql, updata, (unsigned int)strlen(updata));
	if (flag)
	{
		printf("Insert data failure!\n");
		return fAILED;
	}
	printf("Insert data success!\n");
	return SUCCESS;
}
#if 1
/*****************************
**函数功能：对比处理信息对自身进行配置
**参数：apset AP设置的结构体
**返回值：int类型 NEEDNUP-不需要更新配置，NEEDUP-需要更新配置
*****************************/
int Compare_And_Handle_Information(APWLANSET *apset)
{
	if(!apset)
	{
		return 0;
	}
	FILE *rfd = NULL;
	int i,j, type; //type = 0表示相同，type = 1表示不同 
	char cache[64];
	type = NEEDNUP;
	for(i = CON_TXPOWER; i < END; i++)
	{
		memset(cache, '\0', sizeof(cache));
		switch (i)
		{
			case CON_TXPOWER:  //  功率
				rfd = popen(OPENWRT_GET_TXPOWER, "r");
				fscanf(rfd, "%s\n", cache);
				printf("txpower\tis %10s\t%10s\n", (*apset).txpower, cache);
				if (atoi((*apset).txpower) != atoi(cache))
				{
					type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_CHANNEL:  //  信道
				rfd = popen(OPENWRT_GET_CHANNEL, "r");
				fscanf(rfd, "%s\n", cache);
				printf("Channel\tis %10d\t%10d\n", atoi((*apset).channel), atoi(cache));
				if (0 == atoi((*apset).channel))//SVZ模式
				{
				}
				else
				{
					if (((13 == atoi((*apset).channel)) && (0 != atoi(cache))) || ((13 != atoi((*apset).channel)) && (atoi((*apset).channel) != atoi(cache))))
					{
						type = NEEDUP;
					}
				}
				pclose(rfd);
				break;
			case CON_SSID:  // 无线信号
				rfd = popen(OPENWRT_GET_SSID, "r");
				fgets(cache, sizeof(cache), rfd);
				for (j = 0; '\0' != cache[j]; j++)
				{
					if ('\n' == cache[j])
					{
						cache[j] = '\0';
					}
				}
				printf("SSID1\tis %10s\t%10s\n", (*apset).ssid, cache);
				if (strcmp((*apset).ssid, cache))
				{
					type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_ENCTYPT:   // 加密方式
				rfd = popen(OPENWRT_GET_ENCRYPTION, "r");
				fscanf(rfd, "%s\n", cache);
				printf("Encrypt\tis %10s\t%10s\n", (*apset).encrypt, cache);
				if (strstr((*apset).encrypt, "WEP"))
				{
					if (!strstr(cache, "wep"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt, "WPAPSK"))
				{
					if (!strstr(cache, "psk"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt, "WPA2PSK"))
				{
					if (!strstr(cache, "psk2"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt, "NONE"))
				{
					if (!strstr(cache, "none"))
						type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_KEY:  // 密码
				if (strstr((*apset).encrypt, "NONE"))
				{
					printf("encrypt is NONE so key is not important\n");
					break;
				}
				else
				{
					rfd = popen(OPENWRT_GET_ENKEY, "r");
				}
				fscanf(rfd, "%s\n", cache);
				printf("key\tis %10s\t%10s\n", (*apset).key, cache);
				if (strcmp((*apset).key, cache))
				{
					type = NEEDUP;
				}
				if (5 > strlen(cache))
				{
					type = NEEDNUP;
				}
				pclose(rfd);
				break;
			case LIMIT_SIG://最大连接数
				//rfd = popen("iwpriv ath0 get_limitsignal |awk -F ' ' '{print $2}'|cut -c17-20","r");
				rfd = popen(OPENWRT_GET_MAXLISTEN,"r");
				fgets(cache,sizeof(cache), rfd);
				printf("max listen num\tis %3d\t%3d\n", atoi((*apset).max_listen), atoi(cache));
				if ((atoi(cache) != atoi((*apset).max_listen)))
					type = NEEDUP;
				pclose(rfd);
				break;
#if defined (WTP_9557) || defined (WTP_9557_DEF)
			case CON_TXPOWER_TWO:  //  功率
				rfd = popen(OPENWRT_GET_TXPOWER_TWO, "r");
				fscanf(rfd, "%s\n", cache);
				printf("txpower\tis %10s\t%10s\n", (*apset).txpower_t, cache);
				if (atoi((*apset).txpower_t) != atoi(cache))
				{
					type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_CHANNEL_TWO:  //  信道
				rfd = popen(OPENWRT_GET_CHANNEL_TWO, "r");
				fscanf(rfd, "%s\n", cache);
				printf("Channel\tis %10d\t%10d\n", atoi((*apset).channel_t), atoi(cache));
				if (0 == atoi((*apset).channel_t))//SVZ模式
				{
				}
				else
				{
					if (((13 == atoi((*apset).channel_t)) && (0 != atoi(cache))) || ((13 != atoi((*apset).channel_t)) && (atoi((*apset).channel_t) != atoi(cache))))
					{
						type = NEEDUP;
					}
				}
				pclose(rfd);
				break;
			case CON_SSID_TWO:  // 无线信号
				rfd = popen(OPENWRT_GET_SSID_TWO, "r");
				fgets(cache, sizeof(cache), rfd);
				for (j = 0; '\0' != cache[j]; j++)
				{
					if ('\n' == cache[j])
					{
						cache[j] = '\0';
					}
				}
				printf("SSID1\tis %10s\t%10s\n", (*apset).ssid_t, cache);
				if (strcmp((*apset).ssid_t, cache))
				{
					type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_ENCTYPT_TWO:   // 加密方式
				rfd = popen(OPENWRT_GET_ENCRYPTION_TWO, "r");
				fscanf(rfd, "%s\n", cache);
				printf("Encrypt\tis %10s\t%10s\n", (*apset).encrypt_t, cache);
				if (strstr((*apset).encrypt_t, "WEP"))
				{
					if (!strstr(cache, "wep"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt_t, "WPAPSK"))
				{
					if (!strstr(cache, "psk"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt_t, "WPA2PSK"))
				{
					if (!strstr(cache, "psk2"))
						type = NEEDUP;
				}
				if (strstr((*apset).encrypt_t, "NONE"))
				{
					if (!strstr(cache, "none"))
						type = NEEDUP;
				}
				pclose(rfd);
				break;
			case CON_KEY_TWO:  // 密码
				if (strstr((*apset).encrypt_t, "NONE"))
				{
					printf("encrypt is NONE so key is not important\n");
					break;
				}
				else
				{
					rfd = popen(OPENWRT_GET_ENKEY_TWO, "r");
				}
				fscanf(rfd, "%s\n", cache);
				printf("key\tis %10s\t%10s\n", (*apset).key_t, cache);
				if (strcmp((*apset).key_t, cache))
				{
					type = NEEDUP;
				}
				if (5 > strlen(cache))
				{
					type = NEEDNUP;
				}
				pclose(rfd);
				break;
#endif
			default:
				break;
		}
		if(NEEDUP == type)
			break;
	}
	return type;
}
#endif
/*****************************
**函数功能：编写无线配置脚本（当AP的配置与上端不同时，需要更新配置）
**参数：apset AP设置的结构体
**返回值：int类型 fAILED-失败，SUCCESS-成功
*****************************/
int WriteWirelessSetting(APWLANSET set)
{
	FILE *wfd = NULL;
	char cache[256];
	char settingvalue[2048];
	memset(settingvalue, '\0', 2048);
	memset(cache, '\0', 128);
	if (13 == atoi(set.channel))
		sprintf(cache, "%s=%s && %s=auto\n", OPENWRT_SET_TXPOWER, set.txpower, OPENWRT_SET_CHANNEL);
	else
		sprintf(cache, "%s=%s && %s=%s\n", OPENWRT_SET_TXPOWER, set.txpower, OPENWRT_SET_CHANNEL, set.channel);
	strcat(settingvalue, cache);


	memset(cache, '\0', 128);
	sprintf(cache, "%s=\"%s\"\n", OPENWRT_SET_SSID, set.ssid);
	strcat(settingvalue, cache);
	memset(cache, '\0', 128);
	sprintf(cache, "\n%s=\"%s\"\n",OPENWRT_SET_MAXLISTEN, set.max_listen);
	strcat(settingvalue, cache);

	memset(cache, '\0', 128);
	//配置加密方式及密码
	if (strstr(set.encrypt, "NONE"))//不加密
	{
		sprintf(cache, "%s=none\n", OPENWRT_SET_ENCRYPTION);
	}
	else//加密
	{
		if (strstr(set.encrypt, "WPAPSK"))//WPA-PSK加密
		{
			sprintf(cache, "%s=psk\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION, OPENWRT_SET_ENKEY, set.key);
		}
		else if (strstr(set.encrypt, "WPA2PSK"))//WPA2-PSK加密
		{
			sprintf(cache, "%s=psk2\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION, OPENWRT_SET_ENKEY, set.key);
		}
		else //WEP加密
		{
			sprintf(cache, "%s=wep\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION, OPENWRT_SET_ENKEY, set.key);
		}
	}
	strcat(settingvalue, cache);
#if defined (WTP_9557) || defined (WTP_9557_DEF)
	 if (13 == atoi(set.channel_t))
		 sprintf(cache, "%s=%s && %s=auto\n", OPENWRT_SET_TXPOWER_TWO, set.txpower_t, OPENWRT_SET_CHANNEL_TWO);
	else
		sprintf(cache, "%s=%s && %s=%s\n", OPENWRT_SET_TXPOWER_TWO, set.txpower_t, OPENWRT_SET_CHANNEL_TWO, set.channel_t);
	strcat(settingvalue, cache);
	memset(cache, '\0', 128);
	sprintf(cache, "%s=\"%s\"\n", OPENWRT_SET_SSID_TWO, set.ssid_t);
	strcat(settingvalue, cache);

	memset(cache, '\0', 128);
	sprintf(cache, "\n%s=\"%s\"\n",OPENWRT_SET_MAXLISTEN_TWO, set.max_listen);
	strcat(settingvalue, cache);

	memset(cache, '\0', 128);
	//配置加密方式及密码
	if (strstr(set.encrypt_t, "NONE"))//不加密
	{
		sprintf(cache, "%s=none\n", OPENWRT_SET_ENCRYPTION_TWO);
	}
	else//加密
	{
		if (strstr(set.encrypt_t, "WPAPSK"))//WPA-PSK加密
		{
			sprintf(cache, "%s=psk\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION_TWO, OPENWRT_SET_ENKEY_TWO, set.key_t);
		}
		else if (strstr(set.encrypt_t, "WPA2PSK"))//WPA2-PSK加密
		{
			sprintf(cache, "%s=psk2\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION_TWO, OPENWRT_SET_ENKEY_TWO, set.key_t);
		}
		else //WEP加密
		{
			sprintf(cache, "%s=wep\n%s=\"%s\"\n", OPENWRT_SET_ENCRYPTION_TWO, OPENWRT_SET_ENKEY_TWO, set.key_t);
		}
	}
	strcat(settingvalue, cache);
#endif
	memset(cache,'\0',sizeof(cache));
	sprintf(cache, "%s\n%s\n%s\n",OPENWRT_COMMIT_CONF, RES_NET, RES_DHCP);
	strcat(settingvalue, cache);
	memset(cache, '\0', 128);
	//sprintf(cache, "\nsleep 2 && iwpriv ath0 limitsignal \"%s\"\n", set.max_listen);
	strcat(settingvalue, cache);

	wfd = fopen("/tmp/setwlan.sh","w+");
	if (!wfd)
	{
		return fAILED;
	}
	fputs(settingvalue,wfd);
	fclose(wfd);
	chmod("/tmp/setwlan.sh", 00777);
	system("/tmp/setwlan.sh &");
	return SUCCESS;
}

/*****************************
**函数功能：AP升级数据库查询
**参数：mysql-数据库连接字，apmac-AP的mac地址，set-AP设置结构体，myipaddr-AP的IP地址
**返回值：int类型 fAILED-失败，SUCCESS-成功
*****************************/
int Read_AP_UpgradeBS(MYSQL mysql, char *sysname, char *APimgname, char *imgver)
{
	if (!sysname)
	{
		return fAILED;
	}
	MYSQL_RES *result;
	MYSQL_ROW row;
	int flag, t;
	char grepbuf[256];
	memset(grepbuf, '\0', 256);
	memset(imgver, '\0', 8);
	sprintf(grepbuf, "SELECT * from %s where AP_Model like \"%s\" order by AP_Version desc limit 1", DATABS_APUPDATE_TAB, sysname);
	printf("[%s] made...\n", grepbuf);
	//查询成功返回0
	flag = mysql_real_query(&mysql, grepbuf, (unsigned int)strlen(grepbuf));
	if (flag)
	{
		printf("Query failed!\n");
		return fAILED;
	}
	result = mysql_store_result(&mysql); //将全部的查询结果读取到客户端
	row = mysql_fetch_row(result);
	if (!row)   //检索结果集的下一行
	{
		mysql_free_result(result);
		return fAILED;
	}
	for (t = 0; t < mysql_num_fields(result); t++)
	{
		printf("%s\t", row[t]);
	}
	memcpy(imgver, row[3], strlen(row[3])); 
	memcpy(APimgname, row[4], strlen(row[4]));
	printf("\n");
	mysql_free_result(result);
	return SUCCESS;
}


int AP_Manage_From_AC(char *AC_DB_ipaddr)
{
	MYSQL mysql;
	char syscom[64] = { '\0' };
	char apmode[16] = { '\0' };
	char apversion[8] = { '\0' };
	char apimgname[24] = { '\0' };
	printf("start...!\n");
	APWLANSET set;
	int i = 0,count = 0;
	printf("get AP mode...\n");  
#ifdef ANYWIFI_WTP
	Get_AP_Info_ANY(apmode, apversion);//获得AP型号 
#endif
#ifdef DBWIFI_WTP
	Get_AP_Info_DB(apmode, apversion);//获得AP型号 
#endif
	printf("get AC(DBServer) ip address...APmode is %s\n",gapmode);
	i = 0;
	FILE *fd = NULL;
	while (1)
	{
		fd = fopen("/tmp/WTP_quit","w");
		if (fd)
		{
			fclose(fd);
			fd = NULL;
		}
		sleep(40);
		mysql_init(&mysql);
		for (i = 0; i < 2; i++)
		{
			if (SUCCESS == connect_dataBS(&mysql, AC_DB_ipaddr))
			{
				break;
			}
			sleep(3);
		}
		if (i >= 2)
		{
			return fAILED;
		}
		if (fAILED == Read_Manage_DataBS(mysql, gAP_macaddr, &set, gAP_IPaddr, READCONFIG))//获得数据库数据(通过自身mac地址)
		{
			if (fAILED == Read_Manage_DataBS(mysql, DEFAULT_CONFIG_M, &set, gAP_IPaddr, READCONFIG))//获得数据库数据(通用配置)
			{
				printf("ReadDataBS error!\n");
				sleep(2);
				mysql_close(&mysql);
				continue;
			}
		}

		if ('s' == set.refresh[0] || 'S' == set.refresh[0])  // -- S/s表示配置复位
		{
			Read_Manage_DataBS(mysql, DEFAULT_CONFIG_M, &set, gAP_IPaddr, DEFCONFIG);
			Updata_Manage_DataBS(mysql, gAP_macaddr, DEFCONFIG);
			set.refresh[0] = 'y';
		}
		if ('r' == set.upauto[0] || 'R' == set.upauto[0])//R/r表示AP需要重启
		{
			printf("I need reboot \n");
			Updata_Manage_DataBS(mysql, gAP_macaddr, REBOOTAP);
			mysql_close(&mysql);
			system("reboot");
		}
		else if ('n' == set.upauto[0] || 'N' == set.upauto[0])//N/n表示不升级固件
		{
			Updata_Manage_DataBS(mysql, gAP_macaddr, 1000);
			if ('y' == set.refresh[0] || 'Y' == set.refresh[0])    // --Y/n表示自动更新--N/n表示不是自动更新配置
			{
				if (NEEDUP == Compare_And_Handle_Information(&set))
				{
					printf("need up config \n");
					WriteWirelessSetting(set);
				}
				else
					printf("needen't up config\n");
			}
			else
				printf("this system don't setting config auto update!\n");
			mysql_close(&mysql);
		}
		else  // 配置了自动检测升级
		{
			memset(apimgname, '\0', sizeof(apimgname));
			if (SUCCESS == Read_AP_UpgradeBS(mysql, apmode, apimgname, set.imgver))
			{
				printf("apver is %s\t,dbver is %s\n", apversion, set.imgver);
				if (0 > strcmp(apversion, set.imgver))
				{
					Updata_Manage_DataBS(mysql, gAP_macaddr, UPDATASYS);
					printf("update DB--UPSYS\n");
					sprintf(syscom, "/usr/bin/upgrade_set.sh %s %s &", apimgname, set.imgver);
					printf("comand is %s\n", set.imgver);
					system(syscom);
				}
				else
					Updata_Manage_DataBS(mysql, gAP_macaddr, DEFCONFIG);
			}
			mysql_close(&mysql);
		}
		sleep(23);
		if (count >= 5)
		{
			for (count = 0; count < 2; count++)
			{
				if (SUCCESS == Get_ipaddr(gAP_IPaddr))
					break;
				sleep(2);
			}
			count = 0;
		}
		else
			count++;
	}
	return SUCCESS;
}
#if 1
int main(int Argc, char * Argv[])
{
	memset(gAP_macaddr, '\0', sizeof(gAP_macaddr));
	memset(gAP_IPaddr, '\0', sizeof(gAP_IPaddr));
	memset(gAC_IPaddr, '\0', sizeof(gAC_IPaddr));
	int count = 0;
	for (count = 0; count < 2; count++)
	{
		if (SUCCESS == Get_AP_MacAddr(gAP_macaddr))
			break;
		sleep(2);
	}
	if (count >= 2)
		return fAILED;
	for (count = 0; count < 2; count++)
	{
		if (SUCCESS == Get_ipaddr(gAP_IPaddr))
			break;
		sleep(2);
	}
	if (count >= 2)
		return fAILED;
	for (count = 0; count < 2; count++)
	{
		if (SUCCESS == Get_AC_IP(gAC_IPaddr))
			break;
		sleep(2);
	}
	if (count >= 2)
		return fAILED;

	printf("ACIP : %s\nAPIP : %s\nAPMAC : %s\n", gAC_IPaddr, gAP_IPaddr, gAP_macaddr);
	AP_Manage_From_AC(gAC_IPaddr);
	
	return SUCCESS;
}

#endif


